package ua.org.nuos.sdms.clientgui.client.handlers;

import ua.org.nuos.sdms.clientgui.client.context.Messages;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.ErrorMessageEvent;
import ua.org.nuos.sdms.clientgui.client.events.UpdateUserInGroupToLeaderEvent;
import ua.org.nuos.sdms.clientgui.client.listeners.UpdateUserInGroupToLeaderListener;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.Group;
import ua.org.nuos.sdms.middle.util.exception.UpdateEntityException;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 10.04.12
 * Time: 18:24
 * To change this template use File | Settings | File Templates.
 */
public class UpdateUserInGroupToLeaderHandler implements UpdateUserInGroupToLeaderListener {
    @Override
    public void update(UpdateUserInGroupToLeaderEvent event) {
        Group group = AppProxy.getInstance().getModelLocator().getGroup();
        if (group != null) {
            long userId = event.getUserId();
            try {
                AppProxy.getInstance().getServiceLocator().getClientBean().updateUserInGroupStatus(userId, group.getId(), UserInGroup.Type.LEADER);
            } catch (UpdateEntityException e) {
                Logger.getAnonymousLogger().log(Level.WARNING, "Change user user type in group to leader error", e);
                AppProxy.getInstance().getControllerLocator().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.UPDATE_GROUP_ERROR));
            } catch (Exception ex) {
                Logger.getAnonymousLogger().log(Level.WARNING, "Change user user type in group to leader error", ex);
                AppProxy.getInstance().getControllerLocator().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.ACTION_ERROR));
            } finally {
                AppProxy.getInstance().getModelLocator().getGroupContainer().fireListeners();
            }
        }
    }
}
